package net.davidlauzon.assemblandroid.views;

import net.davidlauzon.assemblandroid.R;
import net.davidlauzon.assemblandroid.TimeTrackerApplication;
import net.davidlauzon.assemblandroid.TimeTrackerModel.ACTIVITY;
import net.davidlauzon.utils.IObserver;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ProjectsListingActivity extends ListActivity implements IObserver {
	static private final String TAG = "AssemblaTT";
	
	// GRASP Controller
	private TimeTrackerApplication app;

	private ProgressDialog loadingDialog;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "ProjectListingActivity::onCreate()");

        app = TimeTrackerApplication.getInstance();
        
        loadProjects(false);
    }
     
    private void loadProjects(boolean forceReload) {
    	if (forceReload || !app.projectsReady()) {
    		// Delay loading of records to avoid blocking the UI
	    	// Note: onUpdate() will be called when the task completes
	        loadingDialog = ProgressDialog.show(this, "", "Loading projects. Please wait...", true);
	        app.fetchProjectsLater( this );
    	} else {
    		// If records were already loaded, use the existing data
    		onUpdate();
    	}
    }


    /**
     * Called when projects are loaded (via app.fetchProjectsLater() )
     */
	public void onUpdate() {
		//Log.i(TAG, "onUpdate");
		if (app.projectsReady()) {
			setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, app.projectNamesForList() ));
	
	        ListView lv = getListView();
	        lv.setTextFilterEnabled(true);
	
	        lv.setOnItemClickListener( new OnItemClickListener() {
	        	public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
	        		// When clicked, show a toast with the TextView text
	        		//Log.i(TAG, "OnItemClickListener :: Position:" + Integer.toString(position) + " / id:" + Long.toString(id) + " / " + allTickets.get(position).toString());
	        		
	        		// Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
	        		app.selectProject(position);
	        		
	        		// Launch another activity
	                Intent myIntent = new Intent(ProjectsListingActivity.this, TicketListingActivity.class);
	                ProjectsListingActivity.this.startActivity(myIntent);
	        	}
	        });
	        
	        hideLoadingDialog();
		}
	}

	public void onUpdateFailed(Exception exception) {
		Log.i(TAG, "onUpdateFailed");
		hideLoadingDialog();
	}
	
	private void hideLoadingDialog() {
		if (loadingDialog != null) {
        	loadingDialog.cancel();
        	loadingDialog = null;
        }
	}

	
	/**
	 * Called when the options button (bottom left) is pressed
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.i(TAG, "ProjectsListing::onCreateOptionsMenu()");
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.projects_listing_activity, menu);
		return true;
	}

	// This method is called once the menu is selected
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i(TAG, "ProjectsListing::onOptionsItemSelected()");
		
		switch (item.getItemId()) {
			case R.id.preferences:
				// Launch Preference activity
				startActivity( new Intent(this, EditPreferencesActivity.class) );
				// Some feedback to the user
				Toast.makeText(this, "Here you can maintain your user credentials.", Toast.LENGTH_SHORT).show();
				break;
			
			case R.id.reload:
				loadProjects(true);
				break;
		}
		return true;
	}
    
    /**
     * Called to retrieve per-instance state from an activity before being killed so that the 
     * state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle 
     * populated by this method will be passed to both).
     */
    @Override
    protected void onSaveInstanceState(Bundle state) {
    	super.onSaveInstanceState(state);
        //Log.i(TAG, "::onSaveInstanceState()");
        
        //state.putString("my_value", myEdit.getText().toString() );
    }
    
    /**
     * @see http://stackoverflow.com/questions/456211/activity-restart-on-rotation-android
     * 
     * Called by the system when the device configuration changes while your activity is running. 
     * 
     * Note that this will only be called if you have selected configurations you would like to 
     * handle with the configChanges attribute in your manifest. If any configuration change 
     * occurs that is not selected to be reported by that attribute, then instead of reporting it 
     * the system will stop and restart the activity (to have it launched with the new 
     * configuration).
     * 
     * At the time that this function has been called, your Resources object will have been 
     * updated to return resource values matching the new configuration.
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    	//Log.i(TAG, "::onConfigurationChanged()");
    }
    
    
    /**
     * Called just before the activity starts interacting with the user. 
     * 
     * At this point the activity is at the top of the activity stack, with user input going to it.
     * 
     * Always followed by onPause().
     */
    @Override
    public void onResume() {
    	super.onResume();
        Log.i(TAG, "ProjectListingActivity::onResume()");
    	onUpdate();
    	app.onActivityChanged(ACTIVITY.PROJECTS_LISTING);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ProjectListingActivity::onDestroy()");
    }
}
